package com.ygqh.baby.service.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ygqh.baby.ao.ContractStatus;
import com.ygqh.baby.ao.Message;
import  com.ygqh.baby.ao.QueryInfo;
import  com.ygqh.baby.ao.ResultSet;
import com.ygqh.baby.mapper.AdminSupplementContractDetailMapper;
import com.ygqh.baby.po.AdminContract;
import com.ygqh.baby.po.AdminContractDetail;
import com.ygqh.baby.po.AdminContractExample;
import  com.ygqh.baby.po.AdminSupplementContract;
import  com.ygqh.baby.mapper.AdminSupplementContractMapper;
import com.ygqh.baby.po.AdminSupplementContractDetail;
import com.ygqh.baby.service.AdminContractService;
import com.ygqh.baby.service.AdminSupplementContractDetailService;
import  com.ygqh.baby.service.AdminSupplementContractService;
import org.springframework.beans.BeanUtils;
import  org.springframework.util.Assert;
import java.util.Arrays;
import java.util.stream.Collectors;

import  org.springframework.stereotype.Service;
import  org.springframework.beans.factory.annotation.Autowired;

import  com.ygqh.baby.po.AdminSupplementContractExample;
import  com.ygqh.baby.ao.DataStatus;

@Service
public class AdminSupplementContractServiceImpl implements AdminSupplementContractService{
	
	@Autowired
	private AdminSupplementContractMapper adminSupplementContractMapper;
	@Autowired
	private AdminContractService adminContractService;
	@Autowired
	private AdminSupplementContractDetailService adminSupplementContractDetailService;
	@Autowired
	private AdminSupplementContractDetailMapper adminSupplementContractDetailMapper;

	@Override
	public List<AdminSupplementContract> find() {
		AdminSupplementContractExample example = new AdminSupplementContractExample();
		example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
		return adminSupplementContractMapper.selectByExample(example);
	}

	@Override
	public int findCount() {
		AdminSupplementContractExample example = new AdminSupplementContractExample();
		example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
		return adminSupplementContractMapper.countByExample(example);
	}

	@Override
	public AdminSupplementContract findById(Long id) {
		return adminSupplementContractMapper.selectByPrimaryKey(id);
	}


	

	@Override
	public Message save(AdminSupplementContract adminSupplementContract, String operator) {
		List<AdminSupplementContract> dbAdminSupplementContractList =  findByChangeContractCode(adminSupplementContract.getChangeContractCode());
		if(!dbAdminSupplementContractList.isEmpty()) {
			dbAdminSupplementContractList =  dbAdminSupplementContractList.stream().filter(e->e.getContractStatus().equals(ContractStatus.NotArchived)).collect(Collectors.toList());
			if(dbAdminSupplementContractList.size()>0){
				return Message.error("当前合同存在未归档补充协议。请归档后再进行操作");
			}
		}

		AdminContract adminContract =  adminContractService.findByCode(adminSupplementContract.getChangeContractCode());
		String remark = adminSupplementContract.getRemark();
		adminSupplementContract.setPrePercent(adminContract.getPrePercent());
		adminSupplementContract.setPickPercent(adminContract.getPickPercent());
		adminSupplementContract.setEndPercent(adminContract.getEndPercent());

		adminSupplementContract.setPreMoney(adminContract.getPrePercent().multiply(adminSupplementContract.getContractPrice()).setScale(0, BigDecimal.ROUND_HALF_UP));
		adminSupplementContract.setPickMoney(adminContract.getPickPercent().multiply(adminSupplementContract.getContractPrice()).setScale(0, BigDecimal.ROUND_HALF_UP));
		adminSupplementContract.setEndMoney(adminContract.getEndPercent().multiply(adminSupplementContract.getContractPrice()).setScale(0, BigDecimal.ROUND_HALF_UP));

		adminSupplementContract.setRemark(remark);
		adminSupplementContract.setContractCode(null);
		adminSupplementContract.setCreateBy(operator);
		adminSupplementContract.setCreateTime(new Date());
		adminSupplementContract.setUpdateTime(null);
		adminSupplementContract.setUpdateBy(null);
		adminSupplementContract.setContractStatus(ContractStatus.NotArchived);
		adminSupplementContractMapper.insertSelective(adminSupplementContract);


		List<AdminSupplementContractDetail> details = adminSupplementContract.getSupplementContractDetail();
		details.forEach(e -> {
			e.setSupplementContractId(adminSupplementContract.getId());
			e.setStatus(DataStatus.Valid);
		});
		adminSupplementContractDetailMapper.saveBatch(details);

		if(this.findByCode(adminContract.getContractCode()) == null){
			//复制一条主合同记录
			adminContract = adminContractService.findDetailById(adminContract.getId());
			AdminSupplementContract copySupContract = new AdminSupplementContract();
			BeanUtils.copyProperties(adminContract,copySupContract);
			copySupContract.setChangeContractCode(adminContract.getContractCode());
			adminSupplementContractMapper.insertSelective(copySupContract);
			List<AdminSupplementContractDetail> copyDetails = new ArrayList<>();
			adminContract.getContractDetails().forEach(e -> {
				AdminSupplementContractDetail temp = new AdminSupplementContractDetail();
				BeanUtils.copyProperties(e,temp);
				temp.setSupplementContractId(copySupContract.getId());
				temp.setStatus(copySupContract.getStatus());
				copyDetails.add(temp);
			});
			adminSupplementContractDetailMapper.saveBatch(copyDetails);
		}




		return Message.success("操作成功");
	}

	private List<AdminSupplementContract> findByChangeContractCode(String changeContractCode) {
		AdminSupplementContractExample example = new AdminSupplementContractExample();
		example.createCriteria().andStatusEqualTo(DataStatus.Valid.name()).andChangeContractCodeEqualTo(changeContractCode);
		return adminSupplementContractMapper.selectByExample(example);
	}

	@Override
	public Message update(AdminSupplementContract adminSupplementContract, String operator) {

		adminSupplementContract.setUpdateTime(new Date());
		adminSupplementContract.setUpdateBy(operator);
		List<Long> dbAdminContractDetailIds = this.findDetailById(adminSupplementContract.getId()).getSupplementContractDetail().stream().map(e -> e.getId()).collect(Collectors.toList());
		adminSupplementContractDetailService.deleteSoft(dbAdminContractDetailIds.toArray(new Long[]{}));
		List<AdminSupplementContractDetail> details = adminSupplementContract.getSupplementContractDetail();
		details.forEach(e -> {
			e.setSupplementContractId(adminSupplementContract.getId());
			e.setStatus(DataStatus.Valid);
		});
		adminSupplementContractDetailMapper.saveBatch(details);
		adminSupplementContractMapper.updateByPrimaryKeySelective(adminSupplementContract);
		return Message.success(null);
	}

	@Override
	public ResultSet<AdminSupplementContract> search(QueryInfo queryInfo, String q, String changeContractCode) {
		List<AdminSupplementContract>  list =  adminSupplementContractMapper.selectSuper(queryInfo, q,changeContractCode);
		int count = adminSupplementContractMapper.countSuper(q,changeContractCode);
		ResultSet<AdminSupplementContract> resultSet = new ResultSet<AdminSupplementContract>(count,list);
		return resultSet;
	}

	@Override
	public AdminSupplementContract findByCode(String code) {
		AdminSupplementContractExample example = new AdminSupplementContractExample();
		example.createCriteria().andStatusEqualTo(DataStatus.Valid.name()).andContractCodeEqualTo(code);
		List<AdminSupplementContract> list = adminSupplementContractMapper.selectByExample(example);
		if(list.size() == 1)
			return list.get(0);

		return null;
	}

	@Override
	public Message archivedContract(Long id, String operator, String contractCode) {


		if(this.findByCode(contractCode) != null)
			return Message.error("合同号已经存在");

		AdminSupplementContract adminSupplementContract = this.findDetailById(id);
		adminSupplementContract.setContractStatus(ContractStatus.Archived);
		adminSupplementContract.setUpdateBy(operator);
		adminSupplementContract.setContractCode(contractCode);
		adminSupplementContract.setUpdateTime(new Date());
		adminSupplementContractMapper.updateByPrimaryKey(adminSupplementContract);

		Long contractId =  adminContractService.findByCode(adminSupplementContract.getChangeContractCode()).getId();
		AdminContract adminContract =  adminContractService.findById(contractId);
		adminContract.setContractPrice(adminSupplementContract.getContractPrice());
		adminContract.setQuantity(adminSupplementContract.getQuantity());
		adminContract.setPreMoney(adminSupplementContract.getPreMoney());
		adminContract.setPickMoney(adminSupplementContract.getPickMoney());
		adminContract.setEndMoney(adminSupplementContract.getEndMoney());

		adminSupplementContract.getSupplementContractDetail().forEach(e->{
				AdminContractDetail ad = new AdminContractDetail();
			BeanUtils.copyProperties(e,ad);
			ad.setContractId(e.getSupplementContractId());
			ad.setId(null);
			adminContract.getContractDetails().add(ad);
		});
		adminContractService.update(adminContract,adminContract.getCreateBy());
		
		adminContractService.setSkuCost(contractId);
		return Message.success("操作成功");
	}

	@Override
	public Message deleteSettlementContract(Long id, String operator) {
		AdminSupplementContract adminContract = this.findDetailById(id);
		//如果不是未归档
		if (!adminContract.getContractStatus().name().equals(ContractStatus.NotArchived.name())) {
			return Message.error("删除失败，合同状态必须为未归档");
		}
		List<Long> dbAdminContractDetailIds = this.findDetailById(id).getSupplementContractDetail().stream().map(e -> e.getId()).collect(Collectors.toList());
		adminSupplementContractDetailService.deleteSoft(dbAdminContractDetailIds.toArray(new Long[]{}));
		this.deleteSoft(id);
		return Message.success("操作成功");
	}

	@Override
	public AdminSupplementContract findDetailById(Long id) {
		return adminSupplementContractMapper.findDetailById(id);
	}

	@Override
	public Message updateSettlementRemark(Long id, String operator, String remark) {
		AdminSupplementContract adminContract = findById(id);
		adminContract.setRemark(remark);
		adminContract.setUpdateBy(operator);
		adminContract.setUpdateTime(new Date());
		adminSupplementContractMapper.updateByPrimaryKey(adminContract);
		return Message.success("操作成功");
	}


	@Override
	public int deleteSoft(Long[] ids) {
		Assert.notEmpty(ids);
		AdminSupplementContractExample example = new AdminSupplementContractExample();
		example.createCriteria().andIdIn(Arrays.asList(ids));
		AdminSupplementContract record = new AdminSupplementContract();
		record.setStatus(DataStatus.Delete);

		return adminSupplementContractMapper.updateByExampleSelective(record, example);
	}
	
	@Override
	public int deleteSoft(Long id) {
		return this.deleteSoft(new Long[]{id});
	}

	@Override
	public Message saveOrUpdate(AdminSupplementContract adminSupplementContract, String operator) {
		Message r ;
		if(adminSupplementContract.getId() != null) {
			r = this.update(adminSupplementContract,operator);
		}else {
			r = this.save(adminSupplementContract,operator);
		}
		return r;
	}
	@Override
	public int updateMain(AdminSupplementContract adminSupplementContract){
		return adminSupplementContractMapper.updateByPrimaryKeySelective(adminSupplementContract);
		
	}

}

